package com.iamteer.day23;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

	public static void main(String[] args) {
//		tcpServer();
		chatServer();
	}
	public static void tcpServer() {
		try {
			//1. 建立 TCP 服务
			ServerSocket serverSocket = new ServerSocket(9090);
			//2. 接受客户端的连接
			Socket socket = serverSocket.accept();
			//2. 获取 Socket 输入流对象
			InputStream in = socket.getInputStream();
			byte[] buf = new byte[1024];
			int length = -1;
			length = in.read(buf);
			System.out.println(new String(buf, 0, length));
			OutputStream out = socket.getOutputStream();
			out.write("我是服务端。。。".getBytes());
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void chatServer() {
		try {
			ServerSocket serverSocket = new ServerSocket(9090);
			Socket socket = serverSocket.accept();
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String line = null;
			System.out.println("Running...");
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
